package svckit;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Map;

import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteWatchdog;
import org.apache.commons.exec.PumpStreamHandler;

public class ExeKit
{
	static public class ExeResult
	{
		public String output;
		public String error;
		public int exitCode;
	}
	
	//默认命令超时参数
	static public final long DefaultCmdTimeout=5000l;

	
	static public final String charsetName=System.getProperty("sun.jnu.encoding");
	

	static public ExeResult runAt(String dir,String cmd,String ...args)
	{
		return run(new File(dir),null,DefaultCmdTimeout,cmd,args);
	}
	
	static public ExeResult run(String cmd,String ...args)
	{
		return run(new File("."),null,DefaultCmdTimeout,cmd,args);
	}
	
	static public String runCmd(String cmd)
	{
		ExeResult result=run(new File("."),null,DefaultCmdTimeout,cmd);
		if(result.exitCode==0)
			return result.output;
		return null;
	}
		
	/***
	 * 带超时参数的命令运行（使用apache commons exec库）
	 * @param timeout 超时毫秒数，超过此超时将kill进程
	 * @param cmd 命令
	 * @param args 参数数组
	 * @return
	 */
	static public ExeResult run(File dir,Map<String,String> environment, long timeout,String cmd,String ... args)
	{
		ExeResult result=new ExeResult();
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		ByteArrayOutputStream error = new ByteArrayOutputStream();
		
		CommandLine cl;
		if(args.length==0)
			cl=CommandLine.parse(cmd);
		else
		{
			cl=new CommandLine(cmd);
			for(String arg:args)
				cl.addArgument(arg);
		}
		DefaultExecutor exe=new DefaultExecutor();
        if(dir!=null)
        	exe.setWorkingDirectory(dir);
        if(timeout>0)
        	exe.setWatchdog(new ExecuteWatchdog(timeout));
		exe.setStreamHandler(new PumpStreamHandler(out,error) );
		try
		{
			result.exitCode=exe.execute(cl,environment);
			result.output=out.toString(charsetName);
			result.error=error.toString(charsetName);
		}
		catch (Exception e)
		{
			result.exitCode=-1;
			result.error=e.toString();
			throw new RuntimeException("执行命令错误！");
		}
		return result;
	}
	
	static public void test()
	{
		System.out.println(ExeKit.run("cmd","/C","dir c:\\",">c:\\1.txt"));
		System.out.println(ExeKit.runCmd("cmd  /C 'type c:\\1.txt'"));
	}
}
